from flask import Flask, request
from flask import current_app
from hashlib import md5
import time
import redis
import base.logger
import toml

app = Flask(__name__)

base.logger.__init__(app)

ctx = app.app_context()
ctx.push()

app.logger.error('我打印了一个日志输出')


g_redis_pool = None

def getRedis():
    global g_redis_pool
    if g_redis_pool == None:
        g_redis_pool = redis.ConnectionPool(host="192.168.1.5", port=6379, decode_responses=True)
    return redis.Redis(connection_pool=g_redis_pool)

@app.route('/')
def hello_world():
    return 'Helloworld'

# username=123&password=12345&platform=jieduan&time=90CE3239834ADC08
@app.route("/api/apiauth/_login")
def apiauth_login():
    args = request.args
    if not args["username"] or not args["password"]:
        return "param error"
    redis = getRedis()
    user_key = f"user:{args["username"]}"
    user_info = redis.hgetall(user_key)
    if len(user_info) == 0 : 
        user_info.update(args)
        user_info["uid"] = redis.incr("game_uid")
        del user_info["time"]
        print(f"create user user_info = {user_info}")
        redis.hset(user_key, mapping=user_info)
    else:
         user_info["uid"] = redis.hget(user_key, "uid")
    resp = {
        "error_code" : 0,
        "uid" : user_info["uid"],
        "token" : "52f4d643fc6e41a78e",
        "time" : int(time.time() * 1000),
        "password" : user_info["password"],
        "msg" : "Auth Success!",

    }
    return resp

@app.route("/api/server/_list")
def get_server_list():
    args = request.args
    print(f"args = {args}")
    resp = {
        "error_code" : 0,       # 0 代表成功其余失败
        "msg" : "Success!",     # 错误信息
        "serverlist" : [        # 服务器列表
            {
                "id" : 1,                   # 服务器id
                "name" : "测试1服",         #  // 服务器名字
                "host" : "192.168.1.5",     # 服务器ip或者域名
                "port" : 2008,              # 服务器端口
                "status" : 1,               # 服务器状态
                "recommend" : 1,            # 是否推荐服			
                "charlist" : [
                    {
                        "charid" : 123,       # 角色id
                        "charname" : "test",  # 角色名字
                        "charlevel" : 10,     # 角色等级
                    },
                ]
            }
        ]
    }
    return resp


if __name__ == '__main__':
    app.run(host = '0.0.0.0')
